<template>
	<view class="content">
		<view class="calendar">
			<!-- 第一行：显示年份和月份，并添加上一月和下一月的跳转按钮 -->
			<view class="calendar-header">
				<view class="prev-month" @click="prevMonth">&lt;</view>
				{{ currentYear }}年{{ currentMonth }}月
				<view class="next-month" @click="nextMonth">&gt;</view>
			</view>
			<!-- 第二行：显示周几 -->
			<view class="calendar-weekdays">
				<view class="weekday" v-for="weekday in weekdays" :key="weekday">{{ weekday }}</view>
			</view>
			<!-- 日历主体部分 -->
			<view class="calendar-grid">
				<view v-for="(dateObj, index) in calendarDays" :key="index"
					:class="{ 'calendar-cell': dateObj.isCurrentMonth, 'today': dateObj.isToday, 'event': dateObj.hasEvent, 'selected': isSelected(dateObj) }"
					@click="handleDateClick(dateObj)">
					<view class="date" v-if="dateObj.isCurrentMonth">{{ dateObj.date }}</view>
					<view v-else class="empty"></view>
					<view class="row">
						<view class="add-event-btn" v-if="dateObj.hasEvent &&  !dateObj.isToday"
							@click="addEvent(dateObj)">
							+
						</view>
						<view class="event-text" v-if="dateObj.hasEvent && dateObj.isCurrentMonth">
							{{ dateObj.eventText }}
						</view>
					</view>
				</view>
			</view>
			<view class="add-btn-container">
				<button class="add-date-btn" style="width: 70%;color:aliceblue;background-color:rgb(170, 170, 255);"
					@click="showInputDialog">添加事件时间</button>
			</view>
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				currentYear: 2023,
				currentMonth: 7,
				selectedDate: '',
				selectedDateObj: null, // 存储当前选中的日期对象
				eventDates: ['2023-07-05', '2023-07-10', '2023-07-31'],
				weekdays: ['日', '一', '二', '三', '四', '五', '六'],
				calendarDays: [], // 存储日历数组
				// 用于接收用户输入的时间
				inputDate: '',
			};
		},
		created() {
			this.generateCalendar();
		},
		methods: {
			// 点击日期处理函数
			handleDateClick(dateObj) {
				this.selectedDateObj = dateObj; // 更新选中日期对象
			},
			// 上一月按钮点击事件
			prevMonth() {
				// 省略部分代码
				if (this.currentMonth === 1) {
					this.currentMonth = 12;
					this.currentYear--;
				} else {
					this.currentMonth--;
				}
				this.generateCalendar();
			},
			// 下一月按钮点击事件
			nextMonth() {
				if (this.currentMonth === 12) {
					this.currentMonth = 1;
					this.currentYear++;
				} else {
					this.currentMonth++;
				}
				this.generateCalendar();
			},
			// 点击按钮添加事件
			addEvent(dateObj) {
				const eventText = prompt('请输入事件内容');
				if (eventText) {
					// Find the corresponding date object in the calendarDays array
					const dateObjInArray = this.calendarDays.find((obj) => obj.date === dateObj.date);
					if (dateObjInArray) {
						dateObjInArray.eventText = eventText; // Update the eventText property
					}
				}
			},
			// 生成当前月份的日历数组
			generateCalendar() {
				// 省略部分代码
				const daysInMonth = new Date(this.currentYear, this.currentMonth, 0).getDate();
				const firstDayOfWeek = new Date(this.currentYear, this.currentMonth - 1, 1).getDay();
				this.calendarDays = [];
				for (let i = 1; i <= daysInMonth; i++) {
					const dateStr =
						`${this.currentYear}-${this.currentMonth.toString().padStart(2, '0')}-${i.toString().padStart(2, '0')}`;
					const isToday = dateStr === this.getTodayDateStr(); // Corrected here
					const hasEvent = this.eventDates.includes(dateStr);
					const isSelected = dateStr === this.selectedDate;
					const isCurrentMonth = true;
					const eventText = ''; // 初始化事件内容为空
					this.calendarDays.push({
						date: i,
						isToday,
						hasEvent,
						isSelected,
						isCurrentMonth,
						eventText
					});
				}
				const previousMonthDays = (firstDayOfWeek + 6) % 7;
				const nextMonthDays = (6 - (firstDayOfWeek + daysInMonth) % 7) % 7;
				let date = new Date(this.currentYear, this.currentMonth - 1, 1 - previousMonthDays);
				for (let i = 0; i < previousMonthDays; i++) {
					const isCurrentMonth = false;
					const eventText = ''; // 初始化事件内容为空
					this.calendarDays.unshift({
						date: '',
						isToday: false,
						hasEvent: false,
						isSelected: false,
						isCurrentMonth,
						eventText
					});
				}
				date = new Date(this.currentYear, this.currentMonth, daysInMonth + 1);
				for (let i = 0; i < nextMonthDays; i++) {
					const isCurrentMonth = false;
					const eventText = ''; // 初始化事件内容为空
					this.calendarDays.push({
						date: '',
						isToday: false,
						hasEvent: false,
						isSelected: false,
						isCurrentMonth,
						eventText
					});
				}
			},
			// 获取当天日期的字符串表示（格式：YYYY-MM-DD）
			getTodayDateStr() {
				// 省略部分代码
				const today = new Date();
				const year = today.getFullYear();
				const month = (today.getMonth() + 1).toString().padStart(2, '0');
				const date = today.getDate().toString().padStart(2, '0');
				return `${year}-${month}-${date}`;
			},
			// 判断日期是否为当前选中的日期
			isSelected(dateObj) {
				return this.selectedDateObj && dateObj.date === this.selectedDateObj.date;
			},
			// 点击按钮，弹出输入框以添加时间
			showInputDialog() {
				this.inputDate = ''; // 清空之前的输入
				const input = prompt('请输入日期（格式：YYYY-MM-DD）');
				if (input) {
					// 检查输入是否为合法日期
					const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
					if (dateRegex.test(input)) {
						// 将合法日期添加到eventDates数组中
						this.eventDates.push(input);
						// 重新生成日历以反映更改
						this.generateCalendar();
					} else {
						alert('请输入有效的日期格式（YYYY-MM-DD）！');
					}
				}
			},
		},
	};
</script>
<style>
	.content {
		display: flex;
		justify-content: center;
		align-items: center;
		min-height: 100vh;
	}
	/*日历部分*/
	.calendar {
		width: 300px;
		border: 1px solid #ccc;
		border-radius: 8px;
		padding: 10px;
		margin-bottom: 75%;
	}
	.calendar-header {
		text-align: center;
		font-size: 18px;
		margin-bottom: 10px;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.prev-month,
	.next-month {
		cursor: pointer;
	}
	.calendar-weekdays {
		display: flex;
		justify-content: space-around;
		margin-bottom: 5px;
	}
	.weekday {
		width: 30px;
		text-align: center;
	}
	.calendar-grid {
		display: grid;
		grid-template-columns: repeat(7, 40px);
		grid-template-rows: repeat(6, 40px);
		gap: 2px;
	}
	.calendar-cell {
		display: flex;
		flex-direction: column;
		/* 修改为纵向布局 */
		justify-content: flex-start;
		/* 修改为左对齐以使日期在左上角 */
		align-items: flex-start;
		/* 修改为左对齐以使日期在左上角 */
		width: 40px;
		height: 40px;
		border-radius: 8px;
		cursor: pointer;
		position: relative;
		padding: 2px;
	}
	.empty {
		/* 非本月日期的样式，设置为空白 */
		width: 100%;
		height: 100%;
		color: #ffffff;
	}
	.row {
		display: flex;
		flex-direction: row;
		align-items: center;
	}
	.date {
		/* 修改日期样式，使其较小 */
		font-size: 12px;
		color: #000;
	}
	.event-text {
		/* 添加事件内容的样式，使其较小且浅蓝色背景 */
		font-size: 1px;
		background-color: #c7e1f8;
		padding: 0px;
		border-radius: 4px;
	}
	.add-event-btn {
		/* 修改按钮样式，使其较小 */
		font-size: 2px;
		cursor: pointer;
	}
	.today {
		background-color: #5c95ff;
		color: #fff;
	}
	.event {
		background-color: #ffd700;
	}
	.selected {
		background-color: #a6d0f4;
		color: #fff;
	}
</style>